import {ref, computed, onMounted, watch} from 'vue';
// import ToolAxios from '@/tool/ToolAxios';

let apiTag = ToolAxios.initBaseApi('common','tag');

export default function useTags(defaultCheckTagIds = []) {
    const tags = ref([]);
    defaultCheckTagIds = defaultCheckTagIds || []

    const initList = async () => {
        let res = await apiTag.list({ limit: 999 });
        res.records.filter(item => defaultCheckTagIds.includes(item.id)).forEach(item => item.checked = true);
        tags.value = res.records;
        return tags.value;
    }

    onMounted(() => { initList() })

    const remove = (id) => {
        apiTag.remove(id).then(res => {
            tags.value = tags.value.filter(tag => tag.id !== id);
        });
    }

    const check = (tag) => {
        tag.checked = !tag.checked;
    }

    const checkList = (ids) => {
        tags.value.forEach(item => item.checked = false);
        tags.value.filter(item => ids.includes(item.id)).forEach(item => item.checked = true);
    }

    const checkTags = computed({
        get() {
            return tags.value.filter(item => item.checked).map(item => item.id);
        },
        set(val) {
            checkList(val);
        }
    })

    const add = (name) => {
        if (!name || tags.value.find(item => item.name === name)) {
            return;
        }
        apiTag.add({ name }).then(res => {
            tags.value = [...tags.value, res];
        })
    }

    let watchListen = () => {};

    const addWatchCheck = (listen) => {
        watchListen = listen;
    }

    const transformName = (ids = []) => {
        return tags.value.filter(item => ids.includes(item.id)).map(item => item.name);
    }

    watch(checkTags, (val) => {
        watchListen(val);
    })

    return {
        tags, remove, check, checkTags, add, addWatchCheck, transformName, initList
    }
}